<%-- 
    Document   : newjsp1
    Created on : 2014-3-14, 14:19:16
    Author     : Administrator
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>使用FormData对象向服务器端上传文件</title>   
<script>
function uploadFile() {
    var formData = new FormData();
    var files=document.getElementById("file1").files;
    for (var i = 0;i<files.length;i++) {
        var file=files[i];
        formData.append('myfile[]', file);
    }

    var xhr = new XMLHttpRequest();
    xhr.open('POST','Test', true);
    xhr.onload = function(e) {         
        if (this.status === 200) {
            document.getElementById("result").innerHTML=this.response;
            //document.getElementById("div1").innerHTML=xhr.responseText;
        }
    };
    xhr.send();  
}
</script>
<script type="text/javascript">
	var xmlHttpRequest = null; //声明一个空的对象以接受XMLHttpRequest对象
	function ajaxRequest() {
		if(window.ActiveXObject) {   			//IE的
			xmlHttpRequest = new ActionXObject("Microsoft.XMLHTTP");
		}
		else if(window.XMLHttpRequest) {		//除IE外的
			xmlHttpRequest = new XMLHttpRequest();
		}
		if(xmlHttpRequest !==null) {
			xmlHttpRequest.open("GET", "Test", true);
			//关联好ajax的回调函数
			xmlHttpRequest.onreadystatechange = ajaxCall;
			
			//真正向服务器发送请求
			xmlHttpRequest.send();
		}
	} 
	function ajaxCall() {
		if(xmlHttpRequest.readyState === 4 ) {  		//完全得到服务器的响应
			if(xmlHttpRequest.status === 200) {		//没有异常
				var text = xmlHttpRequest.responseText;
				document.getElementById("div1").innerHTML = text;
			}
		}
	}
</script>
</head>  
    <body>
<h1>使用FormData对象向服务器端上传文件</h1>     
<form id="form1" enctype="multipart/form-data">      
请选择文件<input type="file" id="file1" name="file" multiple><br/>
<input type="button" value="上传文件" onclick="uploadFile();">   

</form>     
<output id="result" ></output>     
<button onclick="ajaxRequest()">request</button>
        <div id="div1"></div>
    </body>
</html>
